import React, { useMemo, useRef } from 'react'
import './App.css'
import { Tldraw, createTLStore, type Editor as TldrawEditor } from '@tldraw/tldraw'
import '@tldraw/tldraw/tldraw.css'
import { bindStoreToYjs, type YjsBinding } from './collab/yjsStore'

const WS_URL = 'ws://localhost:1234'
const ROOM_ID = 'board-1'

function App() {
  const store = useMemo(() => createTLStore(), [])
  const bindingRef = useRef<YjsBinding | null>(null)

  return (
    <div style={{ position: 'fixed', inset: 0 }}>
      <Tldraw
        store={store}
        autoFocus
        onMount={(editor: TldrawEditor) => {
          // 开始与 Yjs 同步（编辑器已挂载，session 准备就绪）
          if (!bindingRef.current) {
            bindingRef.current = bindStoreToYjs({ store, roomId: ROOM_ID, wsUrl: WS_URL })
          }
        }}
        onUnmount={() => {
          bindingRef.current?.teardown()
          bindingRef.current = null
        }}
      />
    </div>
  )
}

export default App
